package com.iretailer.report.analyze.flow;

import com.iretailer.report.analyze.commonModel.PassengerFlowModel;
import com.iretailer.report.analyze.commonUtil.Analyze;
import com.iretailer.report.analyze.commonUtil.ResponeResultType;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpContent;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * @Auther: xjw
 * @Date: 2019/3/9 21:02
 * @Description:
 */
@Component
public abstract class Flow implements Analyze {
    private static final Logger log = LoggerFactory.getLogger(Flow.class);
    @Autowired
    protected FlowInsert flowInsert;
//    private FlowInsert flowInsert = SpringUtils.getBean(com.iretailer.report.analyze.flow.FlowInsert.class);

    @Override
    public ResponeResultType nettyAnalyze(Map<String, Object> paramsMap, Object msg) {
        if (msg instanceof HttpContent) {
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf byteBuf = httpContent.content();
            if (byteBuf != null) {
                PassengerFlowModel pfm = transformation(byteBuf.toString(CharsetUtil.UTF_8), paramsMap);
                return flowInsert.analysisCommon(pfm);
            } else {
                log.error("----- ByteBuf is null. {}", paramsMap.get("remoreAddr"));
                return ResponeResultType.getBadRequest(ResponeResultType.CFLType.CLOSE);
            }
        } else {
            return ResponeResultType.getBadRequest(ResponeResultType.CFLType.CLOSE);
        }
    }

    @Override
    public ResponeResultType springAnalyze(Map<String, Object> paramsMap, Object msg) {
        if (msg instanceof byte[]) {
            PassengerFlowModel pfm = transformation(new String((byte[]) msg, Charset.defaultCharset()), paramsMap);
            return flowInsert.analysisCommon(pfm);
        } else {
            log.error("springAnalyze msg is not byte[]");
            return ResponeResultType.getBadRequest(ResponeResultType.CFLType.CLOSE);
        }
    }

    public abstract PassengerFlowModel transformation(String context, Map<String, Object> paramsMap);
}
